<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="编号" width="180" sortable>
      </el-table-column>
			<el-table-column prop="name" label="名称" width="220" sortable>
			</el-table-column>
      <el-table-column prop="dirPath" label="部门层级ID" width="220" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100"  :formatter="formatState" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 0" style="color: green">正常</span>
          <span v-else-if="scope.row.state == -1" style="color: red">禁用</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门"  sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="pageSize"
                     :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增或修改界面-->
		<el-dialog :title="myTitle" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="管理员" prop="manager">
<!--          <el-input v-model="editForm.manager" auto-complete="off"></el-input>-->
          <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in emps"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="editForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable ></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDeptListPage, removeDept, batchRemoveDept, editDept, addDept } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
				depts: [],
        emps: [],
				total: 0,
        currentPage: 1,
        pageSize:5,
				listLoading: false,
				sels: [],//列表选中列
        myTitle:'',
        deptTree:[],

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,

        //编辑界面的表单校验规则
				editFormRules: {
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入编号', trigger: 'blur' }
          ],
          manager: [
            { required: true, message: '请选择部门管理员', trigger: 'change' }
          ]
				},

				//编辑界面数据
				editForm: {
					id: null,
					name: '',
					sn: '',
          dirPath:'',
					state: 0,
          manager: null,
					parent: null,
          managerId:null,
          parentId:null
				},



			}
		},
		methods: {
			//状态显示转换
			formatState: function (row, column) {
				return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
			},
      //点击页码
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepts();
			},
      //高级查询
      search(){
        this.currentPage =1;
        this.getDepts();
      },
			//获取部门列表
			getDepts() {
				let para = {
					currentPage: this.currentPage,
          pageSize : this.pageSize,
					keyword: this.filters.keyword
				};
				this.listLoading = true;
        this.$http({
          method:"post",
          url:"/dept",
          data:para
        }).then(response=>{
          this.listLoading = false;
            this.depts=response.data.rows;
            this.total=response.data.total;
        }).catch(response=>{

        })
			},

      //获取员工数据
      getEmps(){
        this.$http({
          method:"get",
          url:"/emp"
        }).then(response=>{
          this.emps=response.data;
        }).catch(response=>{

        })
      },

      //获得部门树
      getDeptTree(){
        this.$http({
          method : "get",
          url : "/dept/tree"
        }).then(response=>{
          this.deptTree = response.data;
        })
      },

			//单个删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
          this.$http({
            method : "delete",
            url : "/dept/"+row.id
          }).then(response=>{
            if (response.data.success){
              this.listLoading = false;
              this.$message({
                message: response.data.message,
                type: 'success'
              });
            }else {
              this.$message({
                message: response.data.message,
                type: 'error'
              });
            }
            this.currentPage=1;
            this.getDepts();
          }).catch(response=>{
            this.$message({
              message: '系统繁忙，请稍后重试',
              type: 'error'
            });
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.getDeptTree();
        this.myTitle='编辑';
        this.editFormVisible = true;
        //this.$refs['editForm'].resetFields();
        //拷贝一份row，避免双向绑定引起的数据乱了
        this.editForm = Object.assign({}, row);
        //修改模态框回显需要[1,2]这样的数组，但是dirPath是"/1/2"
        //这里将"/1/2"转换成了[1,2],并赋值给parent属性进行回显
        let dirPath = this.editForm.dirPath;
        if (dirPath){
          let arr = dirPath.split("/");
          let parent = [];
          for (let i=1;i<arr.length-1;i++){
            parent.push(parseInt(arr[i]))
          }
          this.editForm.parent=parent;
        }
			},
			//显示新增界面
			handleAdd: function () {
        this.getDeptTree();
        this.myTitle='新增';
        this.editFormVisible = true;
        //this.$refs['editForm'].resetFields();
        this.editForm = {
          id: null,
          name: '',
          sn: '',
          dirPath:'',
          state: 0,
          manager: null,
          parent: null,
          managerId:null,
          parentId:null
				};
			},

			//执行新增或修改
			editSubmit: function () {
        //主动开启表单校验，防止啥也不填就直接提交
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
              if (para.parent){
                //将数组[1,2]转为对象{id:2}，只要最后一级，作为parent的id
                let temp = para.parent[para.parent.length-1];
                para.parent = {"id" : temp};
                para.parentId = temp;
              }
              para.managerId=para.manager.id;

              this.$http({
                method : "put",
                url : "/dept",
                data : para
              }).then(response=>{
                this.editLoading = false;

                if (response.data.success){
                  this.editFormVisible = false;
                  this.$message({
                    message: response.data.message,
                    type: 'success'
                  });
                }else {
                  this.$message({
                    message: response.data.message,
                    type: 'error'
                  });
                }
                this.currentPage=1;
                this.getDepts();
              }).catch(response=>{
                this.$message({
                  message: '系统繁忙，请稍后重试',
                  type: 'error'
                });
              })
						});
          }
				});
			},

      //批量删除选中的行
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				let ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					//NProgress.start();
          this.$http({
            method : "patch",
            url : "/dept",
            data : ids
          }).then(response=>{
            if (response.data.success){
              this.listLoading = false;
              this.$message({
                message: response.data.message,
                type: 'success'
              });
            }else {
              this.$message({
                message: response.data.message,
                type: 'error'
              });
            }
            this.currentPage=1;
            this.getDepts();
          }).catch(response=>{
            this.$message({
              message: '系统繁忙，请稍后重试',
              type: 'error'
            });
          })
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDepts();
      this.getEmps();
		}
	}

</script>

<style scoped>

</style>